package com.my.app.dbManager.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.my.exception.Message;
import com.my.framework.dao.DbUtils;
import com.my.framework.dao.model.ColumnInfo;
import com.my.framework.dao.model.DatabaseInfo;
import com.my.framework.dao.model.TableInfo;
import com.my.utils.StringUtil;

@Service
public class DbManagerService {

	String TABLE_LIST="select table_name as tableName,table_comment as tableComment from information_schema.TABLES where table_schema='${database}'";
	
	String TABLE="select table_name as tableName,column_name as columnName,is_nullable as nullable,data_type as dataType," + 
			"CHARACTER_MAXIMUM_LENGTH as maxLength,column_comment as columnComment " + 
			"from INFORMATION_SCHEMA.COLUMNS  x where  table_schema='${database}' and table_name='${tableName}' order by ordinal_position ";
	@Autowired
	DbUtils dbUtils;
	public List tableList(DatabaseInfo info) {
		if(StringUtil.isEmpty(info.getDatabase())) {
			throw new Message("库名不能为空");
		}
		String sql=TABLE_LIST.replace("${database}", info.getDatabase());
		return dbUtils.select(info, sql, TableInfo.class);
	}
	

	public TableInfo  getTable(DatabaseInfo info,String tableName) {
		String sql=TABLE.replace("${database}", info.getDatabase())
				.replace("${tableName}", tableName);
		List columns= dbUtils.select(info, sql, ColumnInfo.class);
		TableInfo table=new TableInfo();
		table.setColumns(columns);
		table.setDatabaseInfo(info);
		return table;
	}
	
}
